<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pure 0.2 Epsilon to 0.2 Foxtrot Upgrade</title>
<script type="text/javascript">
function startScrolling() {
	window.scrollBy(0,10);
	interval=setTimeout('startScrolling()',5);
}
</script>
</head>

<body>
<?php
	//Small functions to help us print output
	function report($text) {
		echo($text.'<br />');
	}
	function trace($text) {
		echo('<span style="font-size:10px; margin-left:10px;">'.htmlentities($text,ENT_QUOTES,'UTF-8').'</span><br />');
	}
	function error($text) {
		echo('<span style="color:red; font-weight:bold;">'.htmlentities($text,ENT_QUOTES,'UTF-8').'</span><br />');
	}
	function success($text) {
		echo('<span style="color:green; font-size:11px; margin-left:10px;">'.htmlentities($text,ENT_QUOTES,'UTF-8').'</span><br />');
	}
	
	//Require basic stuff
	require('geshi/geshi.php');
	require('backend/pure.class.php');
	require('backend/fetch.class.php');
	
	//Set up pure
	$_p=new pure('',USE_GESHI_POSTS||USE_GESHI_COMMENTS||USE_GESHI_PAGES);
	
	//Has the upgrade been started
	if(!isset($_GET['start'])) {
		?>
		<h1>Pure 0.2 Delta to 0.2 Foxtrot upgrade</h1>
		<h2>Before starting...</h2>
		<ol>
			<li>Back up your entire site (or if you're lazy, just the tables/ folder)</li>
			<li>Overwrite your existing files on the server with the updated ones</li>
			<li>Give this script write permissions (if you're on the linux sort of server)</li>
		</ol>
		<br />
		If you're ready, <a href="upgrade.php?start">start the upgrade</a> (might take a while if you have a bajillion posts or uploads).
		<?php
	}
	//Actual upgrade process
	else {
		//Scroller javascript start
		echo('<script type="text/javascript">startScrolling();</script>');
		report('Upgrade process started...');
		
		report('Checking if post table is already upgraded...');
		
		/*
		* Does the post table need upgrading?
		*/
		if($_p->tb_posts->isField('categories'))
			trace('Upgrades already performed; moving on...');
		else {
			//
			trace('Yes');
			
			//Add the categories field
			report('Adding "categories" field...');
			
			if($_p->tb_posts->addField('categories')) {
				success('Added');
				
				//If it worked, update all the posts with the Uncategorized category
				report('Adding the "Uncategorized" category to existing posts...');
				$posts=$_p->tb_posts->select('true',array());
				foreach($posts as $postID=>$junk) {
					trace('Updating post #'.$postID.'...');
					$_p->tb_posts->updateRow($postID,array('categories'=>array(0)));
				}
				success(count($posts).' post(s) updated');
				
				//Commit all our changes
				report('Committing changes to posts table');
				if($_p->tb_posts->commit())
					success('changes saved');
				else
					error('changes could not be saved');
			}
			else
				error('Could not add "categories" field to posts table');
		}
		
		/*
		* Attachment system updates
		*/
		
		//Check if the folder exists first
		report('Does the uploads folder exist?');
		if(!is_dir('uploads')) {
			trace('Creating "uploads/" folder...');
			if(mkdir('uploads')!==false) {
				success('"uploads/" created');
			}
			else
				error('could not create "uploads/"');
		}
		else {
			trace('Yes, moving on...');
		}
		
		//Convert attachments
		report('Extracting existing attachments...');
		if($_p->table_exists('uploads')) {
			trace('upload table found');
			if($_p->tb_uploads==NULL) {
				trace('upload table not yet mounted');
				$_p->mount_table('uploads');
				trace('mounted upload table');
			}
			$attachments=$_p->tb_uploads->select('true');
			
			//Stat tracking
			$filesExtracted=0;
			$filesSkipped=0;
			$filesFailed=0;
			
			foreach($attachments as $attachID=>$data) {
				$expectedFilePath='uploads/'.$data['file_name'];
				trace('checking "'.$expectedFilePath.'"...');
				
				//Is the expected path occupied?
				if(file_exists($expectedFilePath)) {
					trace('file at path was found, comparing hashes...');
					$existingHash=md5(file_get_contents($expectedFilePath));
					$newHash=md5($data['file_data']);
					if($existingHash!=$newHash)
						error('File mismatch: existing ('.$existingHash.') v.s. stored('.$newHash/'), this file ("'.$data['file_name'].'") cannot be extracted from the old system, skipping...');
					else
						trace('Files match ('.$existingHash.'), file safely skipped for extraction');
					
					$filesSkipped++;
				}
				else {
					trace('no file was found at the location, extracting file from old system...');
					$handle=fopen($expectedFilePath,'w+');
					fwrite($handle,$data['file_data']);
					fclose($handle);
					$existingHash=md5(file_get_contents($expectedFilePath));
					$newHash=md5($data['file_data']);
					if($existingHash==$newHash) {
						success('file extracted successfully');
						
						$filesExtracted++;
					}
					else {
						error('file ("'.$data['file_name'].'") was corrupted during extraction stored md5('.$newHash.') vs actual md5 ('.$existingHash.')');
						
						$filesFailed++;
					}
				}
			}
			
			//Report upload system upgrade actions
			success($filesExtracted.' file(s) extracted, '.$filesSkipped.' file(s) skipped, '.$filesFailed.' file(s) failed');
		}
		else {
			error('No uploads table found, 0 files extracted');
		}
		/*
		* I suppose we're all done
		*/
		report('All done! The "categories" table will be automatically created when loading the first page of <a href="index.php?">your site</a>. Might want to delete this script too.');
	}
?>
</body>
</html>